<template>
  <!-- 生产节拍表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    :width="!props.isReadonly ? '500px' : '800px'"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目" prop="projectId">
            <el-select
              v-model="formData.projectId"
              placeholder="请选择项目"
              clearable
              filterable
              @change="projectChange"
              style="width: 100%"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="工序" prop="processId">
            <el-select
              v-model="formData.processId"
              placeholder="请选择工序"
              clearable
              :disabled="!formData.projectId"
              filterable
              @change="processChange"
              style="width: 100%"
            >
              <el-option
                v-for="item in processList"
                :key="item.id"
                :label="item.processCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="设备" prop="equipId">
            <el-select
              v-model="formData.equipId"
              placeholder="请选择设备"
              clearable
              filterable
              :disabled="!formData.processId"
              @change="equipChange"
              style="width: 100%"
            >
              <el-option
                v-for="item in equipList"
                :key="item.id"
                :label="item.equipCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="产品型号" prop="modelId">
            <el-select
              v-model="formData.modelId"
              placeholder="请选择产品型号"
              clearable
              filterable
              @change="productChange"
              style="width: 100%"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.productCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="生产节拍（秒）" prop="tactTime">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.tactTime"
              placeholder="请输入生产节拍（秒）"
              clearable
              style="width: 100%"
            />

            <span v-else>{{ formData.tactTime }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-descriptions
      class="margin-top"
      title=""
      :column="2"
      border
      v-if="props.isReadonly"
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">项目名称</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.projectName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">项目编号</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.projectCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">工序名称</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.processName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">工序编号</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.processCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">设备名称</div>
        </template>

        <div style="width: 100%; word-break: break-all">
          {{ formData.equipName }}
        </div>
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div class="cell-item">设备编号</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.equipCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">产品型号名称</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.modelName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">产品型号编号</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.modelCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">生产节拍（秒）</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.tactTime }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import {
  getMdmproductinfosApi,
  getMdmprojectinfosApi,
  getMdminspectiontoolApi,
  getSpecificListApi,
  getMdmProcessEquipApi,
  getMdmProcessProjectApi,
} from "@/utils/commonData";
defineOptions({
  name: "PCMPCMTACTTIMEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  processId: [{ required: true, message: "请选择工序", trigger: "change" }],
  processCode: [],
  processName: [],
  equipId: [{ required: true, message: "请选择设备", trigger: "change" }],
  equipCode: [],
  equipName: [],
  projectId: [{ required: true, message: "请选择项目", trigger: "change" }],
  projectCode: [],
  projectName: [],
  modelId: [{ required: true, message: "请选择产品型号", trigger: "change" }],
  modelCode: [],
  modelName: [],
  tactTime: [
    { required: true, message: "请输入生产节拍（秒）", trigger: "blur" },
    {
      pattern: /^[0-9]*\.?[0-9]+$/,
      message: "请输入数字",
      trigger: "blur",
    },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  processId: "",
  processCode: "",
  processName: "",
  equipId: "",
  equipCode: "",
  equipName: "",
  projectId: "",
  projectCode: "",
  projectName: "",
  modelId: "",
  modelCode: "",
  modelName: "",
  tactTime: "",
  version: "",
  enabled: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  lastUpdateTime: "",
});

watch(
  () => props.data,
  async (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        processId,
        processCode,
        processName,
        equipId,
        equipCode,
        equipName,
        projectId,
        projectCode,
        projectName,
        modelId,
        modelCode,
        modelName,
        tactTime,
        version,
        enabled,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdatedUserId,
        lastUpdatedUserName,
        lastUpdateTime,
      } = newVal;
      Object.assign(formData, {
        id,
        processId,
        processCode,
        processName,
        equipId,
        equipCode,
        equipName,
        projectId,
        projectCode,
        projectName,
        modelId,
        modelCode,
        modelName,
        tactTime,
        version,
        enabled,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdatedUserId,
        lastUpdatedUserName,
        lastUpdateTime,
      });
      await projectChange2(formData.projectId);
      await processChange2(formData.processId);
    }
  }
);

const projectChange2 = async (id) => {
  await getProcessList(id);
};
const processChange2 = async (id) => {
  await getEquipList(id);
};

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.processId = "";
  formData.processCode = "";
  formData.processName = "";
  formData.equipId = "";
  formData.equipCode = "";
  formData.equipName = "";
  formData.projectId = "";
  formData.projectCode = "";
  formData.projectName = "";
  formData.modelId = "";
  formData.modelCode = "";
  formData.modelName = "";
  formData.tactTime = "";
  formData.version = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.lastUpdateTime = "";
}

const loading = ref(false);

/** 生产节拍保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/dmpDosPcm/pcmtacttime/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 通过工序查询设备列表
const equipList = ref(<any>[]);
async function getEquipList(id: string) {
  equipList.value = (await getMdmProcessEquipApi({ processId: id })) || [];
}
function equipChange(id: string) {
  if (id) {
    const current: any =
      equipList.value?.filter((e: any) => e.id === id)[0] ?? {};
    formData.equipCode = current.equipCode || "";
    formData.equipName = current.equipName || "";
  } else {
    formData.equipCode = "";
    formData.equipName = "";
  }
}

// 获取工序列表
const processList = ref<any>([]);
async function getProcessList(id: string) {
  processList.value = (await getMdmProcessProjectApi({ projectId: id })) || [];
}
async function processChange(id: string) {
  formData.equipId = "";
  formData.equipCode = "";
  formData.equipName = "";
  if (id) {
    const current: any =
      processList.value?.filter((e: any) => e.id === id)[0] ?? {};
    formData.processCode = current.processCode || "";
    formData.processName = current.processName || "";
    await getEquipList(id);
  } else {
    formData.processCode = "";
    formData.processName = "";
    equipList.value = [];
  }
}

// 获取项目列表
const projectList = ref<any>([]);
async function getProjectList() {
  projectList.value = (await getMdmprojectinfosApi({})) || [];
}
async function projectChange(id: string) {
  formData.equipId = "";
  formData.equipCode = "";
  formData.equipName = "";
  formData.processId = "";
  formData.processCode = "";
  formData.processName = "";
  if (id) {
    const current: any =
      projectList.value?.filter((e: any) => e.id === id)[0] ?? {};
    formData.projectCode = current.projectCode || "";
    formData.projectName = current.projectName || "";
    await getProcessList(id);
  } else {
    formData.projectCode = "";
    equipList.value = [];
    processList.value = [];
  }
}

// 获取产品型号列表
const productList = ref<any>([]);
async function getProductList() {
  productList.value = (await getMdmproductinfosApi({})) || [];
}
function productChange(id: string) {
  if (id) {
    const current: any =
      productList.value?.filter((e: any) => e.id === id)[0] ?? {};
    formData.modelCode = current.productCode || "";
    formData.modelName = current.productName || "";
  } else {
    formData.modelCode = "";
    formData.modelName = "";
  }
}

onMounted(() => {
  // 获取项目列表
  getProjectList();
  // 获取产品型号列表
  getProductList();
});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style scoped>
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 130px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
